package com.yutel.phone.binh.ui;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.com.xinli.android.service.protocol.BoxSearch;

import com.yutel.phone.binh.R;
import com.yutel.phone.binh.data.vo.Pinyin;
import com.yutel.phone.binh.data.vo.SearchPinyin;
import com.yutel.phone.binh.service.SearchService;
import com.yutel.phone.binh.service.ServiceReceiver;

public class SearchActivity extends BaseActivity implements
		OnItemClickListener, OnScrollListener, ServiceReceiver.Receiver {
	final static String TAG = "SearchActivity";
	private ServiceReceiver mReceiver;
	private EditText searchText;
	private Button searchBtn;
	private TextView searchInfo;
	private ListView lv;
	private int resultLeft = 0;
	private ArrayAdapter<String> pinyinAdapter;
	final private ArrayList<String> pinyinstr = new ArrayList<String>();
	final private ArrayList<Pinyin> pinyins = new ArrayList<Pinyin>();
	View footerView = null;
	private LayoutParams mLayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.WRAP_CONTENT,
			LinearLayout.LayoutParams.WRAP_CONTENT);
	private LayoutParams FFlayoutParams = new LinearLayout.LayoutParams(
			LinearLayout.LayoutParams.MATCH_PARENT,
			LinearLayout.LayoutParams.MATCH_PARENT);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_layout);
		mReceiver = new ServiceReceiver(new Handler());
		mReceiver.setReceiver(this);
		//
		initFooterView();
		searchText = (EditText) findViewById(R.id.search_text);
		searchBtn = (Button) findViewById(R.id.search_btn);
		searchInfo = (TextView) findViewById(R.id.search_info);
		lv = (ListView) findViewById(android.R.id.list);
		pinyinAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, pinyinstr);
		lv.addFooterView(footerView);
		lv.setAdapter(pinyinAdapter);
		lv.setOnItemClickListener(this);
		lv.setOnScrollListener(this);
		lv.removeFooterView(footerView);
		searchBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String st = searchText.getText().toString();
				pinyinstr.clear();
				pinyins.clear();
				Intent intent = new Intent(Intent.ACTION_SYNC, null,
						SearchActivity.this, SearchService.class);
				intent.putExtra(SearchService.EXTRA_STATUS_RECEIVER, mReceiver);
				intent.putExtra(Intent.EXTRA_TEXT, st);
				startService(intent);
				searchBtn.setEnabled(false);
			}
		});
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		Log.i(TAG, "onReceiveResult=" + resultCode);
		switch (resultCode) {
		case SearchService.STATUS_RUNNING:
			lv.addFooterView(footerView);
			break;
		case SearchService.STATUS_FINISHED:
			ArrayList<SearchPinyin> mDataList = (ArrayList<SearchPinyin>) resultData
					.getSerializable(SearchService.class.getSimpleName());
			if (mDataList != null && mDataList.size() > 0) {
				Log.i(TAG, "mDataList=" + mDataList.size());
				SearchPinyin sp = mDataList.get(0);
				resultLeft = sp.getResultLeft();
				boolean sort = "".equals(sp.getPinyin());
				int index = pinyins.size() + 1;
				for (int i = 0; i < sp.getList().size(); i++) {
					Pinyin py = sp.getList().get(i);
					pinyinstr.add(initResult(py, sort, index + i));
					pinyins.add(py);
				}
				searchInfo.setText(getString(R.string.search_result,
						(resultLeft + pinyinstr.size())));
				pinyinAdapter.notifyDataSetChanged();
				searchBtn.setEnabled(true);
				lv.removeFooterView(footerView);
			}
			break;
		case SearchService.STATUS_ERROR:
			searchBtn.setEnabled(true);
			searchInfo.setText(R.string.service_error);
			lv.removeFooterView(footerView);
			break;
		default:
			Log.w(TAG, "warring resultCode=" + resultCode);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Pinyin py = pinyins.get(arg2);
		if (py != null) {
			Intent intent = new Intent(this, DetailActivity.class);
			intent.putExtra(Intent.EXTRA_UID, "v" + py.getVid());
			startActivity(intent);
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem + visibleItemCount == totalItemCount
				&& searchBtn.isEnabled() && resultLeft != 0) {
			searchBtn.setEnabled(false);
			Intent searchIntent = new Intent(Intent.ACTION_SYNC, null, this,
					SearchService.class);
			searchIntent.putExtra(Intent.EXTRA_TEXT, searchText.getText()
					.toString());
			searchIntent.putExtra("index", totalItemCount);
			searchIntent.putExtra(SearchService.EXTRA_STATUS_RECEIVER,
					mReceiver);
			startService(searchIntent);
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

	private void initFooterView() {
		LinearLayout layout = new LinearLayout(this);
		// 设置布局 水平方向
		layout.setOrientation(LinearLayout.HORIZONTAL);
		// 进度条
		ProgressBar progressBar = new ProgressBar(this);
		// 进度条显示位置
		progressBar.setPadding(0, 0, 15, 0);
		// 把进度条加入到layout中
		layout.addView(progressBar, mLayoutParams);
		// 文本内容
		TextView textView = new TextView(this);
		textView.setText("加载中...");
		textView.setGravity(Gravity.CENTER_VERTICAL);
		layout.addView(textView, FFlayoutParams);
		layout.setGravity(Gravity.CENTER);
		LinearLayout loadingLayout = new LinearLayout(this);
		loadingLayout.addView(layout, mLayoutParams);
		loadingLayout.setGravity(Gravity.CENTER);
		footerView = loadingLayout;
	}

	private String initResult(Pinyin py, boolean paihang, int index) {
		StringBuffer sb = new StringBuffer();
		sb.append(py.getValue());
		if (BoxSearch.ResultType.RT_VIDEO.getNumber() != py.getResultType()) {
			sb.append("(").append(type(py)).append(")");
			sb.append(py.getVideoName());
		}
		if (py.getDict() != null) {
			sb.append("(").append(py.getDict().getValue()).append(")");
		}
		if (paihang) {
			sb.insert(0, ":").insert(0, index);
		}
		return sb.toString();
	}

	private String type(Pinyin py) {
		int resultType = py.getResultType();
		if (BoxSearch.ResultType.RT_AREA.getNumber() == resultType) {
			return "地区";
		} else if (BoxSearch.ResultType.RT_OTHER.getNumber() == resultType) {
			return "其他";
		} else if (BoxSearch.ResultType.RT_ACTOR.getNumber() == resultType) {
			if (py.getDict() != null) {
				if (py.getDict().getNum() == 3) {
					return "嘉宾";
				} else if (py.getDict().getNum() == 7) {
					return "歌手";
				} else {
					return "演员";
				}
			} else {
				return "演员";
			}
		} else if (BoxSearch.ResultType.RT_DIRECTOR.getNumber() == resultType) {
			if (py.getDict() != null) {
				if (py.getDict().getNum() == 3) {
					return "主持人";
				} else {
					return "导演";
				}
			} else {
				return "导演";
			}
		} else {
			return "未知类型";
		}
	}
}